package com.ad.aidai.db;

import android.database.sqlite.SQLiteDatabase;

import com.ad.aidai.common.ADApp;
import com.ad.aidai.db.greendao.DaoMaster;
import com.ad.aidai.db.greendao.DaoSession;

/**
 * 数据库管理类
 * <p>
 * Created by Yusxon on 16/11/26.
 */

public class DBManager {
    private static DBManager sInstance;
    private static final String DB_NAME = "AiDai.db";
    private DaoMaster.DevOpenHelper mDevOpenHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    private DBManager() {

    }

    public static DBManager getDB() {
        if (sInstance == null) {
            synchronized (DBManager.class) {
                if (sInstance == null) {
                    sInstance = new DBManager();
                }
            }
        }
        return sInstance;
    }

    /**
     * 初始化数据库
     */
    public void initDB() {
        if (mDevOpenHelper == null) {
            mDevOpenHelper = new DaoMaster.DevOpenHelper(ADApp.getContext(), DB_NAME);
//            Logger.t("DB").i(mDevOpenHelper.getDatabaseName());
        }
    }

    /**
     * 获取可读数据库
     *
     * @return
     */
    public SQLiteDatabase getReadableDatabase() {
        if (mDevOpenHelper == null) {
            initDB();
        }
        return mDevOpenHelper.getReadableDatabase();
    }

    /**
     * 获取可写数据库
     *
     * @return
     */
    public SQLiteDatabase getWritableDatabase() {
        if (mDevOpenHelper == null) {
            initDB();
        }
        return mDevOpenHelper.getWritableDatabase();
    }

    /**
     * 获取DaoMaster
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (mDaoMaster == null) {
            mDaoMaster = new DaoMaster(getWritableDatabase());
        }
        return mDaoMaster;
    }

    /**
     * 获取DaoSession
     *
     * @return
     */
    public DaoSession getDaoSession() {
        if (mDaoSession == null) {
            mDaoSession = getDaoMaster().newSession();
        }
        return mDaoSession;
    }
}